use axum::{
    extract::{Request, State},
    http::StatusCode,
    Json,
};
use tracing::error;
use crate::{
    models::{RegisterRequest, LoginRequest, ApiResponse},
    services::UserService,
};

pub async fn register(
    State(user_service): State<UserService>,
    Json(req): Json<RegisterRequest>,
) -> Result<Json<ApiResponse<crate::models::UserResponse>>, StatusCode> {
    let result = user_service.register(req).await;
    
    match result {
        Ok(response) => Ok(Json(response)),
        Err(e) => {
            error!("注册失败: {:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

pub async fn login(
    State(user_service): State<UserService>,
    Json(req): Json<LoginRequest>,
) -> Result<Json<ApiResponse<crate::models::LoginResponse>>, StatusCode> {
    let result = user_service.login(req).await;
    
    match result {
        Ok(response) => Ok(Json(response)),
        Err(e) => {
            error!("登录失败: {:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

pub async fn get_profile(
    request: Request,
) -> Result<Json<ApiResponse<crate::models::UserResponse>>, StatusCode> {
    let user = request.extensions().get::<crate::models::User>();
    
    match user {
        Some(user) => {
            let user_response: crate::models::UserResponse = user.clone().into();
            Ok(Json(ApiResponse::success(user_response, "获取用户信息成功")))
        }
        None => Err(StatusCode::UNAUTHORIZED),
    }
} 